package com.itheima.pxgl.service.impl;

import com.itheima.pxgl.common.exception.user.UserNotExistsException;
import com.itheima.pxgl.mapper.loginMapper;
import com.itheima.pxgl.entity.pojo.ApUser;
import com.itheima.pxgl.service.loginService;
import com.itheima.pxgl.entity.vo.userVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Random;

@Service
@Slf4j
public class loginServiceImpl implements loginService {
    @Autowired
    private loginMapper loginMapper;

    private static final String CHAR_LIST = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    private static final int CHAR_LIST_SIZE = CHAR_LIST.length();

    /**
     * 用户登录
     *
     * @param userVo
     */
    @Override
    public ApUser login(userVo userVo) {
//  根据用户名获取到用户信息
        String userVoName = userVo.getUsername();
        ApUser apUser = loginMapper.selectByName(userVoName);
//       判断用户密码是否获取到的密码相同
        if (apUser != null && userVo.getPassword() != null) {
            String password = userVo.getPassword();
            password =DigestUtils.md5DigestAsHex((password + apUser.getSalt()).getBytes()) ;
            if (password.equals(apUser.getPassword())) {
                log.info("登录成功{}", apUser);
            } else {
                log.info("密码不匹配");
                throw new UserNotExistsException();
            }
        } else {
            log.info("登陆失败，用户不存在");
            throw new UserNotExistsException();
        }
        return apUser;
    }

    /**
     * 用户注册
     * @param userVo
     */
    @Override
    public void register(userVo userVo) {
        ApUser apUser = new ApUser();
        Random random = new Random();
        String salt = "";
        for (int i = 0; i < 5; i++) {
            int number = random.nextInt(CHAR_LIST_SIZE);
            salt = salt + CHAR_LIST.charAt(number);
        }
        BeanUtils.copyProperties(userVo, apUser);
        apUser.setSalt(salt);
//        将密码加上盐然后使用md5加密然后存入数据库
        String password = DigestUtils.md5DigestAsHex((apUser.getPassword() + apUser.getSalt()).getBytes()) ;
        apUser.setPassword(password);
        loginMapper.insert(apUser);
    }
}
